#include"SList.h"
//动态申请一个节点
SListNode* BuySListNode(SLTDateType x)
{
	SListNode* NewNode = (SListNode*)malloc(sizeof(SListNode));
	if (NewNode == NULL)
	{
		printf("malloc failed");
		exit(-1);
	}
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}
//单链表打印
void SListPrint(SListNode* plist)
{
	SListNode* cur = plist;
	while (cur->next)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULL\n");
}
// 单链表尾插
void SListPushBack(SListNode** pplist, SLTDateType x)
{
	assert(pplist);

	SListNode* NewNode = BuySListNode(x);
	//空链表
	if (*pplist == NULL)
	{
		SListNode* head = *pplist;
		head = NewNode;
	}

	else
	{
		SListNode* tail = *pplist;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = NewNode;
	}
}
// 单链表的头插
void SListPushFront(SListNode** pplist, SLTDateType x)
{
	assert(pplist);
	SListNode* NewNode = BuySListNode(x);
	//空链表
	if (*pplist == NULL)
	{
		SListNode* head = *pplist;
		head = NewNode;
	}
	else
	{
		NewNode->next = *pplist;
		*pplist = NewNode;
	}
}
// 单链表的尾删
void SListPopBack(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	//一个节点
	free(*pplist);
	*pplist = NULL;
	//多个节点
	SListNode* tail = *pplist;
	while (tail->next->next)
	{
		tail = tail->next;
	}
	free(tail->next);
	tail->next = NULL;

}
// 单链表头删
void SListPopFront(SListNode** pplist)
{
	assert(pplist);
	assert(*pplist);
	//一个节点
	free(*pplist);
	*pplist = NULL;
	//多个节点
	SListNode* head = (*pplist)->next;
	free(*pplist);
	*pplist = head;
}
//单链表查找
SListNode* SListFind(SListNode* plist, SLTDateType x)
{
	assert(plist);
	SListNode* cur = plist;
	while (cur)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;

	/*while (cur&&cur->data != x)
	{
		cur = cur->next;
	}
	if (cur == NULL)
		return cur;
	else
		return cur;*/
}
// 单链表在pos位置之后插入x
void SListInsertAfter(SListNode* pos, SLTDateType x)
{
	assert(pos);

	SListNode* NewNode = BuySListNode(x);

	NewNode->next = pos->next;
	pos->next = NewNode;

}
// 单链表删除pos位置之后的值
void SListEraseAfter(SListNode* pos)
{
	assert(pos);
	assert(pos->next);
	SListNode* posnext = pos->next;
	pos->next = posnext->next;
	free(posnext);
	posnext = NULL;
}
//在pos的前面插入
void SLTInsert(SListNode** pplist, SListNode* pos, SLTDateType x)
{
	assert(pos);
	assert(pplist);

	//头插
	if (pos == *pplist)
	{
		SListPushFront(pplist, x);
	}

	//其他
	SListNode* posprve = *pplist;
	while (posprve->next != pos)
	{
		posprve = posprve->next;
	}
	SListNode* NewNode = BuySListNode(x);
	posprve->next = NewNode;
	NewNode->next = pos;

}
//删除pos位置
void SLTErase(SListNode** pplist, SListNode* pos)
{
	assert(pos);
	//头删
	SListPopFront(pplist);

	//其他
	SListNode* posprve = *pplist;
	while (posprve->next != pos)
	{
		posprve = posprve->next;
	}
	posprve->next = pos->next;
	free(pos);
	pos = NULL;



}
